package com.mpale.soa.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Session在线人数监听
 * @author lijian
 * @date 2020/6/17
 */
public class OnlineCountListener implements HttpSessionListener {

    /**
     * 监听Session创建
     */
    @Override
    public void sessionCreated(HttpSessionEvent sessionEvent) {
        ServletContext servletContext = sessionEvent.getSession().getServletContext();
        int onlineCount = 0;
        if (servletContext.getAttribute("onlineCount") != null) {
            onlineCount = Integer.parseInt(servletContext.getAttribute("onlineCount").toString());
        }
        servletContext.setAttribute("onlineCount", ++onlineCount);
    }

    /**
     * 监听Session销毁
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent sessionEvent) {
        ServletContext servletContext = sessionEvent.getSession().getServletContext();
        int onlineCount = 0;
        if (servletContext.getAttribute("onlineCount") != null) {
            onlineCount = Integer.parseInt(servletContext.getAttribute("onlineCount").toString());
        }
        if (onlineCount > 0) {
            servletContext.setAttribute("onlineCount", --onlineCount);
        }
    }
}
